<template>
  <el-card>
    <el-form :inline="true" :model="formInline" style="display: flex">
      <el-form-item>
        <el-input v-model="formInline.username" placeholder="名称" />
      </el-form-item>
      <el-form-item  style="width: 100px">
        <el-select v-model="formInline.status" clearable placeholder="状态">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item  style="flex:1">
        <el-date-picker
            v-model="formInline.createTime"
            type="daterange"
            range-separator="到"
            start-placeholder="创建开始时间"
            end-placeholder="创建结束时间"
        />
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="searchUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="showAddModal">添加用户</el-button>
    <el-button type="primary" @click="showUploadModal">数据导入</el-button>
    <el-button type="primary" @click="exportData">数据导出</el-button>
    <el-popconfirm title="确认删除?" @confirm="batchDeleteUser">
      <template #reference>
        <el-button type="danger" >批量删除</el-button>
      </template>
    </el-popconfirm>
    <el-table :data="users" style="width: 100%"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="username" label="用户名" align="center"></el-table-column>
      <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
      <el-table-column align="center" prop="updateTime" label="更新时间"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template #default="{ row }">
          <el-radio-group v-model="row.status" is-button size="small" @change="updateUserStatus(row)">
            <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showEditModal(row)">编辑</el-button>
          <el-popconfirm title="确认删除?" @confirm="deleteUser(row.id)">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100, 1000, 5000]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-card>

  <!-- 添加用户模态框 -->
  <el-dialog v-model="addDialogVisible" title="添加用户">
    <el-form ref="addFormRef" :model="addFormData" label-width="80px" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="addFormData.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="addFormData.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser(addFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 导入数据-->
  <el-dialog v-model="uploadDialogVisible" title="导入数据">
    <el-upload class="upload-demo" drag :action="uploadURL" multiple :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或者点击上传</div>
    </el-upload>
  </el-dialog>


  <!-- 编辑用户模态框 -->
  <el-dialog v-model="editDialogVisible" title="编辑用户">
    <el-form ref="editFormRef" :model="editFormData" label-width="80px" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="editFormData.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="editFormData.status" is-button>
          <el-radio-button :label="i.label" :value="i.value" v-for="i in options"/>
        </el-radio-group>
      </el-form-item>

    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpdateUser()" >取消</el-button>
          <el-button type="primary" @click="updateUser(editFormRef)">确定</el-button>
        </span>
    </template>
  </el-dialog>

  <!-- 导入数据-->
  <el-dialog v-model="uploadDialogVisible" title="导入数据">
    <el-upload class="upload-demo" drag :action="uploadURL" multiple :on-success="handleUploadSuccess">
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">拖拽文件到此处或者点击上传</div>
    </el-upload>
  </el-dialog>


</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import {fetchUserPage, postUser, putUser, delUser, batchDelUser, exportUserData, fetchUserById} from "@/api/UserApi.js";
import type { ElMessage, UploadProps, FormInstance, FormRules} from 'element-plus'
import {UploadFilled} from "@element-plus/icons-vue";
import { formatDate} from "@/util/dateutil.js";

interface User {
  id: number
  username: string
  password: string
  createTime: string
  updateTime: string
  status: string
}

const users :User[] = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const addFormData :User = reactive({});
let editFormData :User = reactive({});
const multipleSelection = ref<User[]>([])
const uploadDialogVisible = ref(false)
const uploadURL = ref(import.meta.env.VITE_APP_BASE_FILE_API)

const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  username: [
    {
      required: true,
      trigger: 'blur',
    },
    {
      min: 3,
      max: 5,
      message: '字数必须为 3 到 5',
      trigger: 'blur',
      informType: 'warning',
    },
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
    },
    {
      min: 3,
      max: 5,
      message: '字数必须为 3 到 5',
      trigger: 'blur',
      informType: 'warning',
    },
  ]
})

const formInline: User = reactive({})

const options = ref([
  {
    value: '1',
    label: '正常',
  },
  {
    value: '0',
    label: '禁用',
  }
])


const fetchUser = async () => {
  const response = await fetchUserPage(currentPage.value, pageSize.value, {});
  users.value = response.data.records;
  total.value = response.data.total;
};

const addUser = async (formEl: FormInstance | undefined)  => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      return
    }
    await postUser(addFormData);
    addDialogVisible.value = false;
    await fetchUser();
  })
};

const cancelUpdateUser = () => {
  editDialogVisible.value = false;
  fetchUser()
};

const updateUser = async () => {
  await putUser(editFormData);
  editDialogVisible.value = false;
  await fetchUser();
};

const updateUserStatus = async (user: User) => {
  await putUser(user);
  editDialogVisible.value = false;
  await fetchUser();
};

const deleteUser = async (id: number) => {
  await delUser(id)
  await fetchUser();
};

const showAddModal = () => {
  addFormData.value = { id: null, username: '', password: '' };
  addDialogVisible.value = true;
};

const showEditModal = async (row: any) => {
  editFormData = row
  editFormRef.value?.clearValidate()
  editDialogVisible.value = true;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
  fetchUser();
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  fetchUser();
};

// 多选
const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val
}

// 批量删除
const batchDeleteUser = async () => {
  let ids:[] = multipleSelection.value.map((user:User) => user.id)
  if(ids.length==0){
    return ElMessage.error("请先选中！")
  }
  await batchDelUser(ids);
  await fetchUser();
}

// 数据导入
const showUploadModal = () => {
  uploadDialogVisible.value = true
}
const handleUploadSuccess: UploadProps['onSuccess'] = (
    response:any,
    uploadFile:any
) => {
  ElMessage.success("导入成功")
  uploadDialogVisible.value = false
  fetchUser()
}

// 导出数据
const exportData = async () => {
  const res = await exportUserData()
  const blob = new Blob([res.data]);
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  link.href = url
  link.setAttribute('download',  formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')+".csv")
  document.body.appendChild(link)
  link.click()
}

// 条件筛选
const searchUser = async () => {
  let createTime = formInline.createTime
  if(formInline.createTime){
    formInline.createTime = formatDate(formInline.createTime[0], 'yyyy-MM-dd hh:mm:ss')+ ',' + formatDate(formInline.createTime[1], 'yyyy-MM-dd hh:mm:ss')
  }
  const response = await fetchUserPage(currentPage.value, pageSize.value, formInline);
  users.value = response.data.records;
  total.value = response.data.total;
  formInline.createTime = createTime
}



fetchUser();
</script>


<style scoped>
.el-card{
  margin-top: 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  box-shadow: 0 0 0 #ffffff;
  outline: 0;
}
</style>

